/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.storage.web;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.storage.entity.Order;
import com.jeesite.modules.storage.entity.Trade;
import com.jeesite.modules.storage.service.OrderService;
import com.jeesite.modules.storage.service.TradeService;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 交易Controller
 */
@Controller(value = "webtrade")
@RequestMapping(value = "${adminPath}/storage/trade")
public class TradeController extends BaseController {

    @Autowired
    private TradeService tradeService;

    /**
     * 查询列表
     */
    @RequestMapping(value = {"list", ""})
    public String list(Trade trade, Model model) {
        model.addAttribute("trade", trade);
        return "modules/storage/trade/list";
    }

    /**
     * 查询列表数据
     */
    @RequestMapping(value = "listData")
    @ResponseBody
    public Page<Map> listData(Trade trade,HttpServletRequest request, HttpServletResponse response) {
        Page page = new Page<>(request, response);
        return tradeService.getListPageForManage(request.getParameter("name"),request.getParameter("contact"),request.getParameter("phone"),request.getParameter("status"),page.getPageSize(),page.getPageNo());
    }

    /**
     * 导出数据
     */
    @RequestMapping(value = "exportData")
    public void exportData(HttpServletResponse response) {
        try {
            Workbook workbook = getWorkbook("/template/交易 - 大仓库.xlsx");
            Sheet sheet = workbook.getSheetAt(0);
             List<Map> maps =   tradeService.getListForManage(null,null,null,"待到款",Integer.MAX_VALUE,1);
             for (Integer i = 0 ; i < maps.size() ; i ++){
                 Map map = maps.get(i);
                 Row row = getRow(sheet,i + 1);
                 Integer cellNum = 0;
                 getCell(row,cellNum++).setCellValue(i+1);
                 String tradeId = String.valueOf(map.get("tradeId"));
                 getCell(row,cellNum++).setCellValue(tradeId);
                 getCell(row,cellNum++).setCellValue(String.valueOf(map.get("createDate")));
                 getCell(row,cellNum++).setCellValue(String.valueOf(map.get("contact")));
                 getCell(row,cellNum++).setCellValue(String.valueOf(map.get("name")));
                 getCell(row,cellNum++).setCellValue(String.valueOf(map.get("number")));
                 getCell(row,cellNum++).setCellValue(String.valueOf(map.get("phone")));
                 getCell(row,cellNum++).setCellValue(Double.parseDouble(String.valueOf(map.get("amount"))));
                 getCell(row,cellNum++).setCellValue(String.valueOf(map.get("status")));
             }
            exportData(response,"交易 - 大仓库.xlsx",workbook);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 下载导入数据模板
     */
    @RequestMapping(value = "importTemplate")
    public void importTemplate(HttpServletResponse response) {
        importTemplate(response,"交易 - 大仓库.xlsx");
    }

    /*
     * 读取Excel到列表
     */
    private List<Trade> readExcelToList(MultipartFile file){
        try {
            List<Trade> trades = new ArrayList<>();
            Workbook workbook = getWorkbook(file);
            Sheet sheet = workbook.getSheetAt(0);
            for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                Row row = sheet.getRow(rowNum);
                if (row == null  || row.getLastCellNum() < 9) {
                    continue;
                }
                String tradeId = getCellValue(row,1);
                if(StringUtils.isBlank(tradeId)){
                    continue;
                }
                Trade trade = new Trade();
                trade.setId(tradeId);
                trade.setStatus(getCellValue(row,8));
                trades.add(trade);
            }
            return trades;
        } catch (Exception ex) {
            throw ex;
        }
    }

    /*
     * 读取Excel到列表
     */
    private String check(List<Trade> trades){
        return "";
    }

    /**
     * 导入数据
     */
    @ResponseBody
    @PostMapping(value = "importData")
    public String importData(MultipartFile file) {
        try {
            List<Trade> trades = readExcelToList(file);
            String msg = check(trades);
            if(StringUtils.isNotBlank(msg)){
                return renderResult(Global.FALSE, "导入出错:" + msg);
            }
            for (Trade trade : trades){
                tradeService.save(trade);
            }
            return renderResult(Global.TRUE,"导入成功");
        } catch (Exception ex) {
            return renderResult(Global.FALSE, "导入出错:" + ex.getMessage());
        }
    }
}